package edu.hunau.recommend.service.impl;

import edu.hunau.recommend.common.MD5Utils;
import edu.hunau.recommend.common.ResultCodeEnum;
import edu.hunau.recommend.exception.RecommendBusinessException;
import edu.hunau.recommend.mapper.UserMapper;
import edu.hunau.recommend.pojo.User;
import edu.hunau.recommend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author name
 * @creater 2022-09-08-20:11
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findById(Integer id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    //对事务进行管理: 隔离性, 传播性, 只读性, 异常性, 超时性
    @Transactional
    public User register(User user) {
        //对用户的密码进行md5处理
        user.setPassword(MD5Utils.md5(user.getPassword()));

        //需要对密码进行md5的处理
        try{
            //手机号码设置了唯一性约束, 可能存在冲突
            userMapper.insertSelective(user);//执行成功后,user中的id属性获得当前的主键值
            return findById(user.getId());
        }catch (DuplicateKeyException e){//手机号码重复
            throw new RecommendBusinessException(ResultCodeEnum.REGIST_DUP_FAIL);
        }



    }

    @Override
    public User login(String telphone, String password) {
        User user = userMapper.selectByTelphoneAndPassword(telphone, MD5Utils.md5(password));
        if (Objects.isNull(user)){
            //用户名或者密码错误

            throw new RecommendBusinessException(ResultCodeEnum.LOGIN_FAIL);
        }

        return user;
    }

    @Override
    public int countAllUser() {
        return userMapper.countAllUser();
    }
}
